package com.example.cnotebook;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.example.cnotebook.fragment.AddFragment;
import com.example.cnotebook.fragment.HomeFragment;
import com.example.cnotebook.fragment.UserFragment;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private FrameLayout frameHome;
    private LinearLayout layoutHome;
    private LinearLayout layoutAdd;
    private LinearLayout layoutUser;

    private FragmentManager fm;
    private HomeFragment homeFragment;
    private AddFragment addFragment;
    private UserFragment userFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        frameHome = findViewById(R.id.frame);
        layoutHome = findViewById(R.id.layout_home);
        layoutAdd = findViewById(R.id.layout_add);
        layoutUser = findViewById(R.id.layout_user);

        layoutHome.setOnClickListener(this);
        layoutAdd.setOnClickListener(this);
        layoutUser.setOnClickListener(this);

        fm = getSupportFragmentManager();

        layoutHome.performClick();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.layout_add) {
            Intent intent = new Intent(this, AddNoteActivity.class);
            startActivity(intent);
            return;
        }
        FragmentTransaction ft = fm.beginTransaction();
        hideAddFragment(ft);
        switch (v.getId()) {
            case R.id.layout_home:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    ft.add(R.id.frame, homeFragment);
                } else {
                    ft.show(homeFragment);
                }
                break;
            case R.id.layout_user:
                if (userFragment == null) {
                    userFragment = new UserFragment();
                    ft.add(R.id.frame, userFragment);
                } else {
                    ft.show(userFragment);
                }
                break;
        }
        ft.commit();
    }

    public void hideAddFragment(FragmentTransaction ft) {
        if (homeFragment != null) ft.hide(homeFragment);
        if (userFragment != null) ft.hide(userFragment);
    }
}
